package idgen

import (
	"gitee.com/tietang/terrace-go/v2/base"
	"github.com/go-redis/redis/v8"
	log "github.com/sirupsen/logrus"
	"github.com/tietang/props/v3/kvs"
)

//Id生成器实例
var idGeneratorFactory IdGeneratorFactory

func NextId(workName string, code int) string {
	base.Check(idGeneratorFactory)
	gen, err := idGeneratorFactory.GetOrCreate(workName)
	if err != nil {
		log.Error("", err)
	}

	return gen.Next(code)
}

func NextSnowId(workName string) ID {
	base.Check(idGeneratorFactory)
	gen, err := idGeneratorFactory.GetOrCreate(workName)
	if err != nil {
		log.Error("", err)
	}
	id := gen.NextSnowId()
	return id
}

func GetOrCreateIdGenerator(workName string) (IdGenerator, error) {
	gen, err := idGeneratorFactory.GetOrCreate(workName)
	return gen, err
}

func initIdGeneratorFactory(conf kvs.ConfigSource) IdGeneratorFactory {
	opts := &redis.Options{
		//Addr:     conf.GetDefault("redis.addr", "127.0.0.1:6379"),
		//Password: conf.GetDefault("redis.password", ""),
		//DB:       conf.GetIntDefault("redis.database", 0),
		//PoolSize: conf.GetIntDefault("redis.poolSize", 3),
	}
	err := kvs.Unmarshal(conf, opts, "redis")
	if err != nil {
		panic(err)
	}
	log.Infof("connecting redis: %+v", opts)
	client := redis.NewClient(opts)
	log.Info("connected redis:", client.String())
	factory := NewLocalIdGeneratorRedisFactory(client)
	idGeneratorFactory = factory
	return factory
}

type IdGeneratorStarter struct {
	base.BaseStarter
}

func (s *IdGeneratorStarter) Init(ctx base.StarterContext) {
}
func (s *IdGeneratorStarter) Setup(ctx base.StarterContext) {
	initIdGeneratorFactory(ctx.Props())
}
